#include "StdAfx.h"
#include "../OpenCVApp.h"
#include "DrawFaceDetect2.h"


CDrawFaceDetect2::CDrawFaceDetect2(void)
{
}


CDrawFaceDetect2::~CDrawFaceDetect2(void)
{
}
BEGIN_MESSAGE_MAP(CDrawFaceDetect2, CDrawOpenCV)
	ON_WM_PAINT()
END_MESSAGE_MAP()

void CDrawFaceDetect2::DetectAndDraw( IplImage* img ,int flag)
{
    static CvScalar colors[] = 
    {
        {{0,0,255}},
        {{0,128,255}},
        {{0,255,255}},
        {{0,255,0}},
        {{255,128,0}},
        {{255,255,0}},
        {{255,0,0}},
        {{255,0,255}}
    };

    double scale = 1.3;
    IplImage* gray = cvCreateImage( cvSize(img->width,img->height), 8, 1 );
    IplImage* small_img = cvCreateImage( cvSize( cvRound (img->width/scale),
                         cvRound (img->height/scale)),
                     8, 1 );
    int i;

    cvCvtColor( img, gray, CV_BGR2GRAY );
    cvResize( gray, small_img, CV_INTER_LINEAR );
    cvEqualizeHist( small_img, small_img );
    cvClearMemStorage( storage1 );

    if( cascade )
    {
        double t = (double)cvGetTickCount();
        CvSeq* faces = cvHaarDetectObjects( small_img, cascade, storage1,
                                            1.1, 2, 0/*CV_HAAR_DO_CANNY_PRUNING*/,
                                            cvSize(30, 30) );
        t = (double)cvGetTickCount() - t;
        printf( "detection time = %gms\n", t/((double)cvGetTickFrequency()*1000.) );
        for( i = 0; i < (faces ? faces->total : 0); i++ )
        {
            CvRect* r = (CvRect*)cvGetSeqElem( faces, i );
            CvPoint center;
            int radius;
            center.x = cvRound((r->x + r->width*0.5)*scale);
            center.y = cvRound((r->y + r->height*0.5)*scale);
            radius = cvRound((r->width + r->height)*0.25*scale);
            cvCircle( img, center, radius, colors[i%8], 3, 8, 0 );
        }
    }

	//if (flag==1)
	//	cvShowImage( "result", img );
    cvReleaseImage( &gray );
    cvReleaseImage( &small_img );
}


void CDrawFaceDetect2::DealwithFrame()
{
	// TODO: Add your command handler code here
	if(m_pFrame == NULL)
	{			
		return ;
	}
	if(m_pShow == NULL)
	{
		//cvReleaseImage(&m_pShow);	
		CString strPath = CFilyFunction::GetPathByAll(CMediaData::g_FilePath);
		std::wstring wstrPath = strPath.GetBuffer(0);
		std::string cascade_name;
		storage1 = cvCreateMemStorage(0);
		CFilyFunction::WCharToMByte(wstrPath,cascade_name);
		cascade_name = cascade_name + "Cascade\\haarcascade_frontalface_alt.xml";
		cascade = (CvHaarClassifierCascade*)cvLoad( cascade_name.c_str(), 0, 0, 0 );
		
        m_pShow = cvCreateImage( cvSize(m_pFrame->width,m_pFrame->height),
                                IPL_DEPTH_8U, m_pFrame->nChannels );
	}
    if( m_pFrame->origin == IPL_ORIGIN_TL )
        cvCopy( m_pFrame, m_pShow, 0 );
    else
        cvFlip( m_pFrame, m_pShow, 0 );
           
    DetectAndDraw( m_pShow , 1);


}
